/**
 *  Copyright 23.07.2012 oliver.keusemann@googlemail.com
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package de.xelerity.geolessi.types.mixed;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;

public class MaxSizeHashMap<K, V> extends HashMap<K, V> implements Serializable {

	private static final long serialVersionUID = -8515075549227726212L;

	private int MAX;

	private ArrayList<K> mapref;

	public MaxSizeHashMap(int pMaxsize) {
		super();
		mapref = new ArrayList<K>();
		MAX = (pMaxsize <= 0 ? 100 : pMaxsize);
	}

	public V put(K key, V value) {

		if (super.containsKey(key)) {
			return super.put(key, value);
		}

		if (super.size() >= MAX) {
			K todel = mapref.get(0);
			super.remove(todel);
			mapref.remove(0);
		}

		mapref.add(key);
		return super.put(key, value);
	}

	public static void main(String[] args) {

		MaxSizeHashMap<String, String> maxSizeHashMap = new MaxSizeHashMap<String, String>(100);
		for (int i = 0; i < 1000000; i++) {
			maxSizeHashMap.put("String" + i, "d");

			System.out.println(maxSizeHashMap.size());
			String string = maxSizeHashMap.get("String" + i);
			if (string == null) {
				System.err.println("*******************************************************");
			} else {
				System.out.println(string + i);
			}

		}

	}

}
